// 代码块
async function timeout(time) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve();
        }, time);
    })
}

class SuperTask {
    constructor(options) {
        this.watting = []
        this.poolSize = options.poolSize || 2;
        this.runningTaskCount = 0;
    }

    setPoolSize(size) {
        this.poolSize = size;
        this.runTask();
    }

    add(fn) {
        return new Promise((resolve, reject) => {
            this.watting.push({fn, resolve})
            this.runTask();
        })
    }

    runTask() {
        while(this.runningTaskCount < this.poolSize && this.watting.length > 0) {
            const {fn, resolve} = this.watting.shift();
            this.runningTaskCount++;
            fn().then(() => {
                resolve();
                this.runningTaskCount--;
                this.runTask();
            })
        }
    }
}

const superTask = new SuperTask({poolSize: 2});
function addTask(time, name) {
    const label = `任务${name},完成`
    console.log(label);
    superTask.add(() => timeout(time)).then(() => {
        console.timeEnd(label);
    })
}

addTask(10000, 1);
addTask(5000, 2);
addTask(3000, 3);
addTask(4000, 4);
addTask(5000, 5);
setTimeout(() => {
    superTask.setPoolSize(5);
}, 7000);